import React, {useCallback, useEffect, useState} from 'react';
import {
  View,
  Text,
  Image,
  StyleSheet,
  TouchableOpacity,
  FlatList,
  TextInput,
  Dimensions,
  ImageBackground,
  StatusBar,
  Platform,
  SafeAreaView,
} from 'react-native';
import {GridCol, GridRow} from '@hadss/react_native_adaptive_layout/src';
import {
  NavigationSplitContainer,
  NavigationMode,
  NavBarPosition,
} from '@hadss/react_native_adaptive_layout';
import Swiper from 'react-native-swiper';
import CustomTab from '../../components/CustomTab';
import debounce from 'lodash.debounce';
import SearchImage from '../../../assets/svg/Search';
import ResetImage from '../../../assets/svg/Reset';
import MoreImage from '../../../assets/svg/More';
import NavHomeImage from '../../../assets/svg/NavHome';
import NavOwerImage from '../../../assets/svg/NavOwer';
import NavSettingImage from '../../../assets/svg/NavSetting';
import NavSourchImage from '../../../assets/svg/NavSourch';

const App = (props: any) => {
  const isAndroid = Platform.OS === 'android';
  const [currentBp, setCurrentBp] = useState<string>('unknown');

  // 断点
  const onBreakpointChange = useCallback(
    debounce((bp: string) => {
      setCurrentBp(bp);
    }, 300),
    [],
  );
  const [screentViewWidth, setScreentViewWidth] = useState(
    Dimensions.get('window').width,
  );
  useEffect(() => {
    const subscription = Dimensions.addEventListener('change', () => {
      setScreentViewWidth(Dimensions.get('window').width);
      console.log(Dimensions.get('window').width);
    });
    return () => subscription.remove();
  }, [Dimensions.get('window').width]);

  const [text, setText] = useState<string>('');

  // 定义断点
  const getColumns = () => {
    if (screentViewWidth >= 1024) return 4; // 大屏3列
    if (screentViewWidth >= 768) return 3; // 中屏2列
    return 2; // 小屏1列
  };

  const data = [
    {id: 'eqwewqeqw1', name: 'image1'},
    {id: 'eqwewqeqw2', name: 'image3'},
    {id: 'eqwewqeqw3', name: 'image3'},
    {id: 'eqwewqeqw4', name: 'image4'},
    {id: 'eqwewqeqw5', name: 'image5'},
    {id: 'eqwewqeqw6', name: 'image6'},
  ];
  const partImage = [
    {
      partId: '000',
      uri: require('../../../assets/pngs/item_1.png'),
      title: '全部',
    },
    {
      partId: '111',
      uri: require('../../../assets/pngs/item_2.png'),
      title: '周热榜',
    },
    {
      partId: '222',
      uri: require('../../../assets/pngs/item_3.png'),
      title: '免费',
    },
    {
      partId: '333',
      uri: require('../../../assets/pngs/item_4.png'),
      title: '经典',
    },
    {
      partId: '444',
      uri: require('../../../assets/pngs/item_5.png'),
      title: '会员专区',
    },
    {
      partId: '555',
      uri: require('../../../assets/pngs/item_6.png'),
      title: '儿童专区',
    },
    {
      partId: '666',
      uri: require('../../../assets/pngs/item_7.png'),
      title: '直播专区',
    },
    {
      partId: '777',
      uri: require('../../../assets/pngs/item_8.png'),
      title: '健身专区',
    },
    {
      partId: '888',
      uri: require('../../../assets/pngs/item_9.png'),
      title: '课程专区',
    },
  ];

  const images = [
    {
      uri: require('../../../assets/images/image1.png'),
    },
    {
      uri: require('../../../assets/images/image1.png'),
    },
    {
      uri: require('../../../assets/images/image1.png'),
    },
  ];
  const containerPadding = 16;

  const itemGap = 8; // item间距

  const getItemWidth = (index: number) => {
    if (screentViewWidth >= 1024) {
      // 大屏4列
      return (
        (screentViewWidth -
          +96 -
          2 * containerPadding -
          (getColumns() - 1) * itemGap) /
        getColumns()
      );
    } else if (screentViewWidth >= 768) {
      // 中屏3列
      return (
        (screentViewWidth -
          2 * containerPadding -
          (getColumns() - 1) * itemGap) /
        getColumns()
      );
    } else {
      // 小屏2列
      return (
        (screentViewWidth -
          2 * containerPadding -
          (getColumns() - 1) * itemGap) /
        getColumns()
      );
    }
  };
  const marginLeft = (index: number) => {
    if (screentViewWidth >= 1024) {
      // 大屏4列
      if ((index + 1) % getColumns() === 1) {
        return 16;
      } else if ((index + 1) % getColumns() === 2) {
        return itemGap;
      }
      return itemGap;
    } else if (screentViewWidth >= 768) {
      // 中屏3列
      if ((index + 1) % getColumns() === 1) {
        return 16;
      } else if ((index + 1) % getColumns() === 2) {
        return itemGap;
      }
      return itemGap;
    } else {
      // 小屏2列
      if ((index + 1) % getColumns() === 1) {
        return 16;
      }
      return itemGap;
    }
  };
  const marginRight = (index: number) => {
    if (screentViewWidth >= 1024) {
      // 大屏4列
      if ((index + 1) % getColumns() === 0) {
        return 16;
      }
    } else if (screentViewWidth >= 768) {
      // 中屏3列
      if ((index + 1) % getColumns() === 0) {
        return 16;
      }
    } else {
      // 小屏2列
      if ((index + 1) % getColumns() === 0) {
        return 16;
      }
    }
  };
  const getPadding = () => {
    if (currentBp === 'lg') {
      return 100;
    } else if (currentBp === 'md') {
      return 65;
    } else if (currentBp === 'sm') {
      return 65;
    } else if (currentBp === 'xs') {
      return 19;
    }
  };

  const getWidth = () => {
    if (currentBp === 'lg') {
      return '50%';
    } else if (currentBp === 'md') {
      return '60%';
    } else if (currentBp === 'sm') {
      return 65;
    } else if (currentBp === 'xs') {
      return 38;
    }
  };

  const HomeScreen = () => {
    return (
      <View style={{flex: 1, backgroundColor: '#fff'}}>
        {/* <Text>Current Breakpoint: {currentBp}</Text> */}
        <GridRow
          onBreakpointChange={onBreakpointChange}
          style={styles.gridRow}
          columns={12}>
          {/* 大屏侧边栏 */}
          {currentBp === 'lg' && (
            <GridCol span={{xs: 0, sm: 0, md: 0, lg: 1}} offset={0} order={0}>
              <View style={styles.bottomWrapLg}>
                <TouchableOpacity style={styles.bottomItemLg}>
                  <Image
                    style={styles.bottomImg}
                    source={require('../../../assets/pngs/nav_1.png')}
                  />
                  <Text style={styles.bottomTitleActive}>首页</Text>
                </TouchableOpacity>
                <TouchableOpacity style={styles.bottomItemLg}>
                  <Image
                    style={styles.bottomImg}
                    source={require('../../../assets/pngs/nav_2.png')}
                  />
                  <Text style={styles.bottomTitle}>动态</Text>
                </TouchableOpacity>
                <TouchableOpacity style={styles.bottomItemLg}>
                  <Image
                    style={styles.bottomImg}
                    source={require('../../../assets/pngs/nav_3.png')}
                  />
                  <Text style={styles.bottomTitle}>会员购</Text>
                </TouchableOpacity>
                <TouchableOpacity style={styles.bottomItemLg}>
                  <Image
                    style={styles.bottomImg}
                    source={require('../../../assets/pngs/nav_4.png')}
                  />
                  <Text style={styles.bottomTitle}>我的</Text>
                </TouchableOpacity>
              </View>
            </GridCol>
          )}
          {/* 消息列表页 */}
          {(currentBp === 'sm' ||
            currentBp === 'md' ||
            currentBp === 'xs' ||
            currentBp === 'lg') && (
            <GridCol
              span={{xs: 12, sm: 12, md: 12, lg: 11}}
              offset={0}
              order={0}>
              {/* 顶部搜索 */}
              {(currentBp === 'md' || currentBp === 'lg') && (
                <View
                  style={{
                    width: '100%',
                    flexDirection: 'row',
                    paddingHorizontal: 16,
                    alignItems: 'center',
                    justifyContent: 'center',
                    height: 72,
                    // position: 'absolute',
                    zIndex: 10,
                    backgroundColor: '#FFF',
                  }}>
                  <View
                    style={{
                      height: 40,
                      width: getWidth(),
                      overflow: 'hidden',
                      marginRight: 16,
                      alignItems: 'center',
                    }}>
                    <CustomTab />
                  </View>
                  <View style={{flex: 1, flexDirection: 'row', zIndex: 10}}>
                    <View
                      style={{
                        position: 'absolute',
                        top: 12,
                        zIndex: 1,
                        left: 12,
                      }}>
                      {isAndroid ? (
                        <SearchImage style={{width: 16, height: 16}} />
                      ) : (
                        <Image
                          style={{width: 16, height: 16}}
                          source={require('../../../assets/pngs/search.png')}
                        />
                      )}
                    </View>
                    <TextInput
                      placeholder="搜索..."
                      onChangeText={text => setText(text)}
                      value={text}
                      style={{
                        flex: 1,
                        borderRadius: 20,
                        height: 40,
                        backgroundColor: 'rgba(0, 0, 0, 0.05)',
                        paddingLeft: 30,
                      }}
                    />
                    <View
                      style={{
                        marginLeft: 16,
                        justifyContent: 'center',
                        alignItems: 'center',
                        width: 40,
                        height: 40,
                        borderRadius: 40,
                        backgroundColor: 'rgba(0, 0, 0, 0.05)',
                      }}>
                      {isAndroid ? (
                        <ResetImage style={styles.bottomImg} />
                      ) : (
                        <Image
                          style={styles.bottomImg}
                          source={require('../../../assets/pngs/clock.png')}
                        />
                      )}
                    </View>
                    <View
                      style={{
                        justifyContent: 'center',
                        alignItems: 'center',
                        width: 40,
                        height: 40,
                        borderRadius: 40,
                        backgroundColor: 'rgba(0, 0, 0, 0.05)',
                        marginLeft: 8,
                      }}>
                      {isAndroid ? (
                        <MoreImage style={{width: 14, height: 14}} />
                      ) : (
                        <Image
                          style={{width: 14, height: 14}}
                          source={require('../../../assets/pngs/more.png')}
                        />
                      )}
                    </View>
                  </View>
                </View>
              )}
              {(currentBp === 'sm' || currentBp === 'xs') && (
                <>
                  <View
                    style={{
                      flexDirection: 'row',
                      paddingHorizontal: 16,
                      paddingTop: 24,
                      paddingBottom: 8,
                    }}>
                    <View
                      style={{
                        flex: 1,
                        overflow: 'hidden',
                        marginRight: 16,
                      }}>
                      <CustomTab />
                    </View>
                    <View
                      style={{
                        justifyContent: 'center',
                        alignItems: 'center',
                        width: 40,
                        height: 40,
                        borderRadius: 40,
                        backgroundColor: 'rgba(0, 0, 0, 0.05)',
                      }}>
                      {isAndroid ? (
                        <MoreImage style={{width: 14, height: 14}} />
                      ) : (
                        <Image
                          style={{width: 14, height: 14}}
                          source={require('../../../assets/pngs/more.png')}
                        />
                      )}
                    </View>
                  </View>
                  <View style={[styles.inputContent]}>
                    <View
                      style={{
                        position: 'absolute',
                        top: 22,
                        zIndex: 1,
                        left: 30,
                      }}>
                      {isAndroid ? (
                        <SearchImage style={{width: 16, height: 16}} />
                      ) : (
                        <Image
                          style={{width: 16, height: 16}}
                          source={require('../../../assets/pngs/search.png')}
                        />
                      )}
                    </View>
                    <TextInput
                      placeholder="搜索..."
                      onChangeText={text => setText(text)}
                      value={text}
                      style={{
                        flex: 1,
                        borderRadius: 20,
                        height: 40,
                        backgroundColor: 'rgba(0, 0, 0, 0.05)',
                        paddingLeft: 34,
                      }}
                    />
                    <View style={{paddingLeft: 17}}>
                      {isAndroid ? (
                        <ResetImage style={styles.bottomImg} />
                      ) : (
                        <Image
                          style={styles.bottomImg}
                          source={require('../../../assets/pngs/clock.png')}
                        />
                      )}
                    </View>
                  </View>
                </>
              )}
              {/* 滚动 */}
              <FlatList
                data={data}
                numColumns={getColumns()}
                key={`columns-${getColumns()}`}
                contentContainerStyle={{
                  justifyContent: 'flex-start', // 自动均匀分布
                }}
                showsVerticalScrollIndicator={false}
                ListHeaderComponent={
                  <View style={{width: '100%'}}>
                    <View
                      style={{
                        height: 200,
                        paddingHorizontal: 16,
                        borderRadius: 20,
                        overflow: 'hidden',
                      }}>
                      {(currentBp == 'sm' || currentBp === 'xs') && (
                        <Swiper
                          style={{height: 200, borderRadius: 20}}
                          showsPagination={true}
                          loop={true}
                          autoplay={true}
                          loadMinimal={true}
                          autoplayTimeout={3}
                          removeClippedSubviews={false}
                          dotColor="rgba(255,255,255,0.5)"
                          activeDotColor="#fff">
                          {images.map((uri: any, index: number) => (
                            <Image
                              key={index}
                              source={require('../../../assets/images/image1.png')}
                              style={{
                                width: '100%',
                                height: '100%',
                                borderRadius: 20,
                              }}
                              resizeMode="cover"
                            />
                          ))}
                        </Swiper>
                      )}
                      {(currentBp == 'md' || currentBp === 'lg') && (
                        <FlatList
                          data={data}
                          renderItem={({item}: any) => (
                            <Image
                              style={{
                                width: 360,
                                height: 200,
                                borderRadius: 16,
                                marginRight: 16,
                              }}
                              source={require('../../../assets/images/image1.png')}
                            />
                          )}
                          horizontal
                          showsHorizontalScrollIndicator={false}
                          keyExtractor={item => item.id}
                          style={styles.content}
                        />
                      )}
                    </View>
                    <View
                      style={{
                        height: 65,
                        marginVertical: 16,
                      }}>
                      <FlatList
                        data={partImage}
                        horizontal
                        nestedScrollEnabled={true}
                        keyExtractor={item => item.partId}
                        showsHorizontalScrollIndicator={false}
                        renderItem={({item, index}: any) => (
                          <TouchableOpacity
                            style={{
                              flex: 1,
                              justifyContent: 'center',
                              alignItems: 'center',
                              paddingLeft: index === 0 ? 16 : 0,
                              paddingRight: getPadding(),
                              paddingVertical: 10,
                            }}>
                            <View
                              style={{
                                width: 40,
                                height: 40,
                                backgroundColor: '#f8e6da',
                                alignItems: 'center',
                                justifyContent: 'center',
                                borderRadius: 40,
                              }}>
                              <Image
                                source={item.uri}
                                style={{width: 20, height: 20}}
                              />
                            </View>
                            <Text style={{fontSize: 12, textAlign: 'center'}}>
                              {item.title}
                            </Text>
                          </TouchableOpacity>
                        )}
                      />
                    </View>
                  </View>
                }
                keyExtractor={item => item.id.toString()}
                ListFooterComponent={
                  currentBp === 'lg' ? (
                    <View style={{marginBottom: 40}}></View>
                  ) : null
                }
                renderItem={({index}: any) => (
                  <View
                    style={{
                      width: getItemWidth(index),
                      marginLeft: marginLeft(index),
                      marginRight: marginRight(index),
                      overflow: 'hidden',
                      marginBottom: 10,
                      flex: 1,
                    }}>
                    <View style={{height: 150}}>
                      <ImageBackground
                        source={require('../../../assets/images/image1.png')}
                        style={{
                          width: getItemWidth(index),
                          height: 150,
                          flex: 1,
                          borderRadius: 15,
                          overflow: 'hidden',
                        }}
                        resizeMode="cover">
                        <View
                          style={{
                            width: 50,
                            height: 20,
                            backgroundColor: '#ff8c1a',
                            borderBottomRightRadius: 25,
                          }}>
                          <Text
                            style={{
                              fontSize: 12,
                              textAlign: 'center',
                              color: '#ffffff',
                              lineHeight: 20,
                            }}>
                            正片
                          </Text>
                        </View>
                        <View
                          style={{
                            position: 'absolute',
                            bottom: 5,
                            right: 8,
                            width: 30,
                            height: 20,
                            backgroundColor: '#979da6',
                            borderRadius: 6,
                          }}>
                          <Text
                            style={{
                              fontSize: 12,
                              textAlign: 'center',
                              color: '#ffffff',
                              lineHeight: 20,
                            }}>
                            9.0
                          </Text>
                        </View>
                      </ImageBackground>
                    </View>
                    <View>
                      <Text
                        numberOfLines={1}
                        ellipsizeMode="tail"
                        style={{
                          marginTop: 4,
                          fontWeight: 'bold',
                          fontSize: 14,
                        }}>
                        {'这是超人的水准'}
                      </Text>
                      <Text
                        numberOfLines={1}
                        ellipsizeMode="tail"
                        style={{
                          marginTop: 4,
                          fontWeight: 'normal',
                          fontSize: 12,
                        }}>
                        {'中秋节端午节重阳节泼水节节日快乐节日快乐'}
                      </Text>
                    </View>
                  </View>
                )}
              />

              {/* Bottom */}
              {(currentBp == 'sm' ||
                currentBp == 'md' ||
                currentBp == 'xs') && (
                <View style={styles.bottomWrap}>
                  <TouchableOpacity style={styles.bottomItem}>
                    {isAndroid ? (
                      <NavHomeImage style={styles.bottomImg} />
                    ) : (
                      <Image
                        style={styles.bottomImg}
                        source={require('../../../assets/pngs/nav_1.png')}
                      />
                    )}
                    <Text style={styles.bottomTitleActive}>首页</Text>
                  </TouchableOpacity>
                  <TouchableOpacity style={styles.bottomItem}>
                    {isAndroid ? (
                      <NavSourchImage style={styles.bottomImg} />
                    ) : (
                      <Image
                        style={styles.bottomImg}
                        source={require('../../../assets/pngs/nav_2.png')}
                      />
                    )}

                    <Text style={styles.bottomTitle}>动态</Text>
                  </TouchableOpacity>
                  <TouchableOpacity style={styles.bottomItem}>
                    {isAndroid ? (
                      <NavSettingImage style={styles.bottomImg} />
                    ) : (
                      <Image
                        style={styles.bottomImg}
                        source={require('../../../assets/pngs/nav_3.png')}
                      />
                    )}

                    <Text style={styles.bottomTitle}>会员购</Text>
                  </TouchableOpacity>
                  <TouchableOpacity style={styles.bottomItem}>
                    {isAndroid ? (
                      <NavOwerImage style={styles.bottomImg} />
                    ) : (
                      <Image
                        style={styles.bottomImg}
                        source={require('../../../assets/pngs/nav_4.png')}
                      />
                    )}
                    <Text style={styles.bottomTitle}>我的</Text>
                  </TouchableOpacity>
                </View>
              )}
            </GridCol>
          )}
        </GridRow>
      </View>
    );
  };
  return (
    <>
      <StatusBar backgroundColor={'#FFFFFF'} barStyle="dark-content" />
      <SafeAreaView style={{flex: 1}}>
        <NavigationSplitContainer
          mode={NavigationMode.Stack}
          navBarPosition={NavBarPosition.Start}
          navBarWidth={400}
          navBarWidthRange={[240, 400]}
          minContentWidth={200}
          onNavBarStateChange={newState => {
            console.log('onNavBarStateChange: ', newState);
          }}
          onNavigationModeChange={newMode => {
            console.log('onNavigationModeChange: ', newMode);
          }}>
          <HomeScreen></HomeScreen>
        </NavigationSplitContainer>
      </SafeAreaView>
    </>
  );
};

const styles = StyleSheet.create({
  gridRow: {
    flex: 1,
  },
  title: {
    color: 'rgba(0, 0, 0, 0.9)',
    fontSize: 26,
    fontWeight: '700',
  },
  content: {
    flex: 1,
  },
  contentMain: {
    color: 'rgba(0, 0, 0, 0.9)',
    fontSize: 16,
  },
  contentSecondary: {
    color: 'rgba(0, 0, 0, 0.6)',
    fontSize: 14,
  },
  item: {
    height: 72,
    flexDirection: 'row',
    alignItems: 'center',
  },
  inputContent: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    height: 60,
    paddingHorizontal: 16,
    paddingVertical: 16,
  },
  itemImgWrap: {
    position: 'relative',
  },
  itemImg: {
    width: 40,
    height: 40,
    margin: 18,
    borderRadius: 20,
  },
  itemContent: {
    flex: 1,
    justifyContent: 'center',
  },
  itemTime: {
    marginRight: 16,
    color: 'rgb(24, 36, 49)',
    fontSize: 12,
    opacity: 0.5,
  },
  unreadBubbleFirstWrap: {
    position: 'absolute',
    right: 16,
    top: 11,
    backgroundColor: '#FFF',
    width: 20,
    height: 20,
    borderRadius: 10,
    alignItems: 'center',
    justifyContent: 'center',
  },
  unreadBubbleFirst: {
    borderRadius: 8,
    backgroundColor: 'rgb(232, 72, 38)',
    color: 'rgb(255, 255, 255)',
    fontSize: 10,
    textAlign: 'center',
    width: 16,
    height: 16,
    lineHeight: 16,
  },
  unreadBubbleSecondWrap: {
    position: 'absolute',
    right: 10,
    top: 11,
    backgroundColor: '#FFF',
    width: 31,
    height: 20,
    borderRadius: 10,
    alignItems: 'center',
    justifyContent: 'center',
  },
  unreadBubbleSecond: {
    borderRadius: 8,
    backgroundColor: 'rgb(232, 72, 38)',
    fontSize: 10,
    textAlign: 'center',
    width: 27,
    height: 16,
    lineHeight: 16,
    color: '#fff',
  },

  bottomWrap: {
    flexDirection: 'row',
    backgroundColor: 'rgba(241, 243, 245, 0.8)',
    paddingVertical: 10,
    paddingBottom: 28,
    zIndex: 11,
  },
  bottomWrapLg: {
    flexDirection: 'column',
    width: 96,
    height: '100%',
    backgroundColor: 'rgba(241, 243, 245, 0.8)',
    alignItems: 'center',
    justifyContent: 'center',
    zIndex: 11,
  },
  bottomImg: {
    width: 24,
    height: 24,
    // marginBottom: 4,
  },
  bottomItem: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  bottomItemLg: {
    alignItems: 'center',
    justifyContent: 'center',
    height: 100,
  },
  bottomTitle: {
    color: 'rgba(0, 0, 0, 0.6)',
    fontSize: 10,
  },
  bottomTitleActive: {
    color: '#fe8d00',
    fontSize: 10,
  },
  input: {
    width: 236,
    height: 40,
    borderWidth: 0,
    borderRadius: 20,
    backgroundColor: 'white',
    paddingHorizontal: 15,
    paddingVertical: 0,
  },
});

export default App;
